package com.idelan.commonMessage.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.SignatureException;

public class MD5 {
	
	 /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @return 签名结果
     */
    public static String sign(String text, String key) {
    	text = text + key;
        return DigestUtils.md5Hex(getContentBytes(text, "UTF-8"));
    }
    
    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param sign 签名结果
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
    	text = text + key;
    	String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    	if(mysign.equals(sign)) {
    		return true;
    	}
    	else {
    		return false;
    	}
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException 
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    public static void main(String[] args) {
    	//http://192.168.30.39:8080/userPc/getModel?appId=delan1001&id=1?sign=eb742e8cb2be1e07862112c7452526c0

    	int id = 1;
    	
    	String appId = "delan1001";
    	String appsecret = "456697909e12ec928298089cdf13cee7";
    	
    	StringBuilder builder = new StringBuilder();
    	builder.append("appId="+appId);
    	builder.append("&id="+id);
    	
    	String str = builder.toString();
    	String sign =  MD5.sign(str, appsecret);
    	
    	if("eb742e8cb2be1e07862112c7452526c0".equals(sign)){
    		System.out.println("签名成功");
    	}else{
    		System.out.println("签名失败");
    		
    	}
        System.out.println("签名结果为："+sign);
        }
}
